﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WeiTalk.Controls;
using WeiTalk.Interfaces.Sina;
using RestSharp;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;

namespace WeiTalk
{
    public partial class WeiBoShow : PhoneApplicationPage
    {
        public static WeiBoControl ParentControl { get; set; }
        int page = 1;
        string since_id = "0";
        bool isUpdating = false;
        StackPanel spGetMore = null;
        StackPanel weiBoContent = null;
        Button btnGetMore = null;
        bool isCommentsLoaded = false;
        const string WeiBoCotentName = "WeiBoCotent";
        const string WeiBoCommentName = "WeiBoComment";
        PullAndDownControl reflashControl = new PullAndDownControl();
        string locker = "1";
        ImageViewer imageViewer = new ImageViewer();
        public WeiBoShow()
        {
            InitializeComponent();
            if (weiBoContent == null)
            {
                weiBoContent = new StackPanel();
                weiBoContent.Orientation = System.Windows.Controls.Orientation.Vertical;
            }
        }

        private void InitGetMoreControl()
        {
            if (spGetMore == null)
            {
                spGetMore = new StackPanel();
                btnGetMore = new Button();
                btnGetMore.FontSize = 18.667d;
                btnGetMore.FontWeight = FontWeights.Bold;
                btnGetMore.BorderThickness = new Thickness(0d);
                btnGetMore.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                btnGetMore.Background = new SolidColorBrush(Color.FromArgb(127, 91, 142, 169));
                btnGetMore.Click += (s, e) => {
                    page += 1;
                    GetComments(ParentControl.Id, false);
                };
                spGetMore.Children.Add(btnGetMore);
            }
            if (!weiBoContent.Children.Contains(spGetMore))
            {
                weiBoContent.Children.Add(spGetMore);
            }
        }

        private bool IsBack()
        {
            return
                spGetMore != null &&
                !spGetMore.Children.Contains(reflashControl);
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!IsBack())
            {
                //reset
                if (ParentControl != null)
                {
                    ParentControl.sbSelected.Stop();
                }
                ptComments.SelectionChanged += (s, ev) =>
                {
                    Pivot parentControl = (Pivot)s;
                    if (parentControl.SelectedItem != null &&
                        !isCommentsLoaded &&
                        ((PivotItem)parentControl.SelectedItem).Name == WeiBoCommentName)
                    {
                        GetComments(ParentControl.Id, false);
                        isCommentsLoaded = true;
                        this.ApplicationBar.IsVisible = false;
                    }
                    else if (parentControl.SelectedItem != null &&
                        ((PivotItem)parentControl.SelectedItem).Name == WeiBoCommentName)
                    {
                        this.ApplicationBar.IsVisible = false;
                    }
                    else if (parentControl.SelectedItem != null)
                    {
                        this.ApplicationBar.IsVisible = true;
                    }
                };
                InitGetMoreControl();
                CreateWeiBoContent();
                CreateWeiBoComments();
            }
        }

        private void EnableRefreshControl()
        {
            if (!spGetMore.Children.Contains(reflashControl))
            {
                reflashControl.Busy = true;
                reflashControl.EnableImage = false;
                reflashControl.Text = "";
                spGetMore.Children.Add(reflashControl);
            }
        }

        private void ResetRefreshControl()
        {
            if (spGetMore.Children.Contains(reflashControl))
            {
                reflashControl.Busy = false;
                spGetMore.Children.Remove(reflashControl);
            }
        }

        private void GetComments(string id, bool update)
        {
            if (isUpdating)
            {
                return;
            }
            if (ParentControl.CommentCount != "0")
            {
                btnGetMore.Content = "正在获取数据...";
                EnableRefreshControl();
            }
            else
            {
                WeiBoUtility.ShowToast("休息一下吧，没有新的评论...");
                btnGetMore.Content = "暂无评论,点击更新...";
                ResetRefreshControl();
                return;
            }
            var client = new RestClient();
            CommentAPI comments = new CommentAPI(client);
            if (!update)
            {
                since_id = "0";
            }
            comments.CommentShow(result =>
            {
                List<WeiTalk.SinaEntities.Comment.Entity> data = ((WeiTalk.SinaEntities.Comment.Collection)result.Data).Comments;

                AddCommentItems(data, update, weiBoContent);
                ResetRefreshControl();
            }, id, page, since_id);
           
        }

        private void CreateWeiBoContent()
        {
            WeiBoControl control = CopyWeiBo();
            ScrollViewer svWeiBoConetent = new ScrollViewer();
            svWeiBoConetent.Margin = new Thickness(12, 0, 12, 0);
            svWeiBoConetent.Content = control;
            WeiBoCotent.Content = svWeiBoConetent;
        }

        private void CreateWeiBoComments()
        {
            ScrollViewer svWeiBoComments = new ScrollViewer();
            svWeiBoComments.Margin = new Thickness(12, 0, 12, 0);
            svWeiBoComments.Content = weiBoContent;
            svWeiBoComments.Name = Guid.NewGuid().ToString();
            WeiBoComment.Content = svWeiBoComments;
        }

        private void AddCommentItems(List<WeiTalk.SinaEntities.Comment.Entity> data, bool isRefresh, StackPanel parentControl)
        {
            lock (locker)
            {
                isUpdating = true;
            }
            if (data == null || data.Count == 0)
            {
                lock (locker)
                {
                    isUpdating = false;
                }
                WeiBoUtility.ShowToast("休息一下吧，没有新的评论...");
                btnGetMore.Content = "暂无评论,点击更新...";
                return;
            }
            if (parentControl.Children.Contains(spGetMore))
            {
                Dispatcher.BeginInvoke(() =>
                {
                    parentControl.Children.Remove(spGetMore);
                });
            }
            int index = 0;
            foreach (var item in data)
            {
                WeiBoCommentControl control = new WeiBoCommentControl();
                if (index == 0)
                {
                    since_id = item.ID;
                }
                index++;
                control.Name = string.Format("{0}_{1}", item.ID, Guid.NewGuid());
                try
                {
                    WeiBoUtility.RetrieveImage(item.User.ProfileImageUrl, (s) =>
                    {
                        BitmapImage bi = new BitmapImage();
                        bi.SetSource(s);
                        bi.CreateOptions = BitmapCreateOptions.DelayCreation;
                        control.ProfileImageUrl = bi;
                    }, Dispatcher.BeginInvoke);
                }
                catch { }
                control.Id = item.ID;
                control.Text = item.Text;
                control.UserName = item.User.Name;
                control.Source = item.Source;
                control.CreatedAt = item.CreatedAt;
                //control.CommentCount = item.ReplyComment.
                Dispatcher.BeginInvoke(() =>
                {
                    parentControl.Children.Add(control);
                });
            }
            Dispatcher.BeginInvoke(() =>
            {
                parentControl.Children.Add(spGetMore);
                btnGetMore.Content = "点击获取更多...";
            });
            lock (locker)
            {
                isUpdating = false;
            }
        }

        private WeiBoControl CopyWeiBo()
        {
            WeiBoControl weiBo = new WeiBoControl();
            weiBo.Name = Guid.NewGuid().ToString();
            weiBo.Id = ParentControl.Id;
            weiBo.RetweetedThumbnailPic = ParentControl.RetweetedThumbnailPic;
            weiBo.Text = ParentControl.Text;
            weiBo.UserId = ParentControl.UserId;
            weiBo.UserName = ParentControl.UserName;
            weiBo.CreatedAt = ParentControl.CreatedAt;
            weiBo.ProfileImageUrl = ParentControl.ProfileImageUrl;
            weiBo.RetweetedCommentCount = ParentControl.RetweetedCommentCount;
            if (ParentControl.ThumbnailPic != null)
            {
                weiBo.ThumbnailPic = ParentControl.ThumbnailPic;
            }
            weiBo.RetweetedContent = ParentControl.RetweetedContent;
            weiBo.RetweetedId = ParentControl.RetweetedId;
            weiBo.RetweetedSource = ParentControl.RetweetedSource;

            weiBo.RetweetedUserId = ParentControl.RetweetedUserId;
            weiBo.RetweetedUserName = ParentControl.RetweetedUserName;
            weiBo.RetweetedRepostsCount = ParentControl.RetweetedRepostsCount;
            weiBo.Source = ParentControl.Source;
            weiBo.CommentCount = ParentControl.CommentCount;
            weiBo.RepostsCount = ParentControl.RepostsCount;
            weiBo.OriginalPic = ParentControl.OriginalPic;
            weiBo.RetweetedOriginalPic = ParentControl.RetweetedOriginalPic;
            weiBo.ThumbnailPicClick += new ImageClickEventHandler(ThumbnailPicClick);
            weiBo.RetweetedThumbnailPicClick += new ImageClickEventHandler(ThumbnailPicClick);
            return weiBo;
        }

        private void ThumbnailPicClick(object sender, ImageEventArgs e)
        {
            ApplicationBarIconButton mibtnLoading = FindLoadingButton();
            if (mibtnLoading == null)
            {
                return;
            }
            WeiBoUtility.ShowToast("正在下载图片...");
            WeiBoControl control = (WeiBoControl)sender;
            mibtnLoading.IsEnabled = false;
            WeiBoUtility.RetrieveImageByOne(e.ImageUrl, s =>
            {
                mibtnLoading.IsEnabled = true;
                mibtnLoading.Text = Constant.loadedMsg;
                imageViewer.Source = s;
                imageViewer.Control = control;
                imageViewer.IsReady = true;
                imageViewer.IsGif = Regex.IsMatch(e.ImageUrl, ".gif$", RegexOptions.IgnoreCase);
                WeiBoUtility.ShowToast("下载完成,点击查看...");
                this.ApplicationBar.IsVisible = true;
            }, Dispatcher.BeginInvoke);
        }

        private ApplicationBarIconButton FindLoadingButton()
        {
            foreach (object button in this.ApplicationBar.Buttons)
            {
                if (button is ApplicationBarIconButton &&
                    (((ApplicationBarIconButton)button).Text == Constant.loadingMsg ||
                    ((ApplicationBarIconButton)button).Text == Constant.loadedMsg))
                {
                    return (ApplicationBarIconButton)button;
                }
            }
            return null;
        }

        private void ResetLoadingControl()
        {
            imageViewer.IsReady = false;
            ApplicationBarIconButton mibtnLoading = FindLoadingButton();
            if (mibtnLoading == null)
            {
                return;
            }
            mibtnLoading.Text = Constant.loadingMsg;
            mibtnLoading.IsEnabled = false;
        }

        private void ImageViewer_Click(object sender, EventArgs e)
        {
            if (imageViewer.IsReady)
            {
                ImageViewerPage.Source = imageViewer.Source;
                ImageViewerPage.ParentControl = imageViewer.Control;
                ImageViewerPage.IsGif = imageViewer.IsGif;
                NavigationService.Navigate(new Uri("/ImageViewerPage.xaml", UriKind.Relative));
            }
            ResetLoadingControl();
        }
    }
}